package org.example.filter;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.User;
import org.example.service.UserService;
import org.example.utils.HttpCode;
import org.example.utils.JwtUtil;
import org.example.utils.ResponseUtil;
import org.example.utils.Result;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


/**
 * 重写授权的逻辑
 */
@Slf4j
public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {


    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        // 没有token,视为未登录
        if (!StringUtils.hasText(token)) {
            chain.doFilter(request,response);
            return;
        }
        Claims claims = JwtUtil.decryptToken(token);
        if (claims == null){
            ResponseUtil.out(response, Result.fail(HttpCode.TOKEN_ERROR));
            return;
        }

        Long id = Long.valueOf(claims.getId());
        String account = claims.getSubject();
        String permissions = (String) claims.get("permissions");
        log.info("正在授权中-----id为: [{}] , 账号为: [{}] , 具有的权限: {}" ,id,account,permissions);

        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(account,token,
                        AuthorityUtils.commaSeparatedStringToAuthorityList(permissions))
        );
        chain.doFilter(request,response);
    }
}
